import { Component, OnInit } from '@angular/core';
import Common from '../../common/common';
import {TipService} from "../../services/tip.service";
import {ActivatedRoute, Router} from "@angular/router";
import {ExtendHttpService} from "../../services/extend-http.service";

@Component({
  selector: 'app-forgot-pwd-step1',
  templateUrl: './forgot-pwd-step1.component.html',
  styleUrls: ['./forgot-pwd-step1.component.css']
})
export class ForgotPwdStep1Component implements OnInit {

  isLoading = false;
  tipType = 'error';
  info = {mobile: '', code: ''};
  codeFlag = false;
  codeTime = 120;
  codeStr = '0s';
  intervalId = null;
  constructor(
    private tipService: TipService,
    private router:Router,
    private activatedRoute: ActivatedRoute,
    private extendHttp: ExtendHttpService
  ) { }

  ngOnInit() {
    cBack =()=> {
      $('#btn-back').trigger('click');
    }
  }

  // 获取验证码
  getCode() {
    if (!this.info.mobile.trim()) {
      this.tipService.change(true, '请输入手机号');
      return;
    }
    if (!Common.mobileReg(this.info.mobile)) {
      this.tipService.change(true, '手机号格式不正确');
      return;
    }

    this.isLoading = !this.isLoading;
    this.extendHttp.post('/agentApp/login/forgetPwd', {mobile: this.info.mobile}).subscribe(response => {
      let res = response.json();
      if (res.code == '0') {
        this.codeFlag = true;
        this.isLoading = !this.isLoading;
        this.intervalId = setInterval(() => {
          this.codeTime = this.codeTime - 1;

          if (this.codeTime === 0) {
            clearInterval(this.intervalId);
            this.codeTime = 120;
            this.codeFlag = false;
          }
          this.codeStr = this.codeTime + 's';
        }, 1000);
      } else {
        this.tipService.change(true, res['message']);
        this.isLoading = !this.isLoading;
      }
    }, error => {
      this.tipService.change(true, '系统繁忙，操作失败！');
      this.isLoading = !this.isLoading;
    });
  }

  onSubmit() {
    if (!this.info.mobile.trim()) {
      this.tipService.change(true, '请输入手机号');
      return;
    }
    if (!Common.mobileReg(this.info.mobile)) {
      this.tipService.change(true, '手机号格式不正确');
      return;
    }
    if (!this.info.code.trim()) {
      this.tipService.change(true, '请输入获取到的验证码');
      return;
    }
    this.router.navigate(['/forgot-pwd-step2'], {queryParams: {mobile: this.info.mobile, code: this.info.code}});
  }

  ngOnDestroy() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  }

}
